when Conditions
The when directive allows Jenkins pipelines to run stages conditionally.
This is one of the most used and most misused pipeline features.
What Is the when Directive?​
The when directive controls whether a stage executes or is skipped.
It is evaluated:
- Before the stage starts
- On the controller
- Based on pipeline context
Basic Syntax​
stage('Deploy') {
when {
branch 'main'
}
steps {
sh 'deploy.sh'
}
}
Common when Conditions​
Branch Condition​
when {
branch 'main'
}
Runs only on the specified branch.
Expression Condition​
when {
expression {
return params.RUN_DEPLOY == true
}
}
Allows custom Groovy logic.
Environment Condition​
when {
environment name: 'ENV', value: 'prod'
}
Not Condition​
when {
not {
branch 'develop'
}
}
Any / All Conditions​
when {
anyOf {
branch 'main'
branch 'release'
}
}
when {
allOf {
branch 'main'
expression { params.DEPLOY == true }
}
}
beforeAgent Option​
when {
beforeAgent true
branch 'main'
}
- Prevents agent allocation if condition fails
- Saves resources
Strongly recommended for expensive agents.
Common Mistakes​
- Putting
wheninsidesteps - Using complex Groovy logic inline
- Forgetting
beforeAgent - Hardcoding branch names
Best Practices​
- Keep conditions simple
- Prefer parameters over hardcoding
- Use
beforeAgent truewhen possible - Move complex logic to shared libraries
Interview Traps​
-
When is
whenevaluated?
→ Before stage execution -
Does
whenconsume an agent?
→ Only ifbeforeAgentis false -
Can
whenskip stages?
→ Yes